﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DrillOnline.Controllers
{
    [Authorize()]
    public class ExamineController : _BaseController
    {
        //
        // GET: /Player/
        //GET:			/Player/			wait,sesioninfo,joinsession
        [AllowAnonymous]
        public ActionResult Index()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return Redirect("~/Examine/Login");
            }
            var cs = GetCurrentSession();
            if (null == cs || !UserTenant.DrillSubjects.Any(s => s.ID == cs.Subject.ID)) { return Redirect("~/Account/LogOff"); }


            return View(cs);
        }
        //GET: 	/Player/Login				groupAndUserList,login        
        [AllowAnonymous]
        public ActionResult Login()
        {
            var cs = GetCurrentSession();
            if (null == cs || !UserTenant.DrillSubjects.Any(s => s.ID == cs.Subject.ID)) { return Redirect("~/Account/LogOff"); }
            //if (!cs.IsReady) { return Redirect("Index"); }

            var m = cs;

            return View(m);
        }
        //POST:	/Player/Login				groupAndUserList,login
        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(string user, string pwd)
        {
            var cs = GetCurrentSession();
            if (null == cs || !UserTenant.DrillSubjects.Any(s => s.ID == cs.Subject.ID)) { return Redirect("~/Account/LogOff"); }

            var u = cs.ActorGroups.Where(v => v.Examiners != null).SelectMany(v => v.Examiners).FirstOrDefault(v => v.ActorKey.ToLower() == user.ToLower() && v.Password == pwd);
            if (null != u)
            {
                System.Web.Security.FormsAuthentication.SetAuthCookie(u.ActorKey, false);
                return Redirect("Index");
            }
            else
            {
                ModelState.AddModelError("loginfailed", new Services.SiteException("登录失败."));
                return View(cs);
            }
        }
        //GET:			/Player/CtrlPanel			eventlist,media,pin,ZhiShu,reply

        //protected override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    var cs = GetCurrentSession();
        //    if (null == cs || !UserTenant.DrillSubjects.Contains(cs.Subject)) { return ; }
        //    if (cs.ActorGroups.Any(v => v.Examiners.Any(j => j.ActorKey == SiteUser.Identity.Name)))
        //    {
        //        base.OnActionExecuting(filterContext);
        //    }
        //    else {
        //        throw new Services.SiteException("您未被登记为评估员，请与演练组织者联系处理。");
        //    }

        //}

        // GET: /Examine/
        //GET:			/Examine/SessionInfo		wait,sesioninfo,joinsession
        //public ActionResult Index()
        //{
        //    var cs = GetCurrentSession();
        //    if (null == cs || !UserTenant.DrillSubjects.Contains(cs.Subject)) { return Redirect("~/Account/LogOff"); }
        //    //if (!cs.IsReady) { return Redirect("Index"); }

        //    var m = cs;

        //    return View(m);
        //}



        //GET:			/Examine/CtrlPanel			ruleList,relation-events,relation-reply(s),pointing,Commit
        public ActionResult CtrlPanel()
        {
            var cs = GetCurrentSession();
            if (null == cs || !UserTenant.DrillSubjects.Any(s => s.ID == cs.Subject.ID)) { return Redirect("~/Account/LogOff"); }
            if (!cs.IsReady) { return Redirect("Index"); }


            //var rs = DB.SubjectEvaluationRules.Where(v => v.SubjectID == cs.Subject.ID);
            //var m = new Tuple<Services.DrillScenarios, IEnumerable<Models.SubjectEvaluationRule>>(cs, rs);
            return View(cs);
        }
        //POST:			/Examine/CtrlPanel			ruleList,relation-events,relation-reply(s),pointing,Commit
        [HttpPost]
        public ActionResult CtrlPanel(string eventid, int value,string valuetitle)
        {
            var cs = GetCurrentSession();
            if (null == cs || !UserTenant.DrillSubjects.Any(s => s.ID == cs.Subject.ID)) { return Redirect("~/Account/LogOff"); }
            if (!cs.IsReady) { return Redirect("Index"); }
            var scene=cs.SceneList.FirstOrDefault(v => v.Model.ID == Guid.Parse(eventid));
            //var r = cs.Messages.FirstOrDefault(v=>v.TargetEventID==eventid);
            //if (null == r) return Json(false);

            if (scene == null) throw new ArgumentOutOfRangeException("eventid not find :" + eventid);

            //if (scene.Group != ScenariosUser.GroupKey) throw new ArgumentException("access to this rule is deny for u");
            if(scene.Evaluation ==null){
                var msg=cs.Messages.Where(v=>v.TargetEventID==scene.Model.ID.ToString("N")).OrderBy(v=>v.RealTime).LastOrDefault();
                var e = new Models.TrainningEvaluation()
                {
                    Id = Guid.NewGuid(),
                    RuleID=Guid.Parse("6652dddd-12e3-45cd-83bc-52bcfb88bf45"),
                    ExaminerName = SiteUser.Identity.Name,
                    Group = ScenariosUser.GroupKey,
                    ReplyContent =msg==null?"":msg.Content,
                    SessionID = cs.Session.ID,
                    SessionName = cs.Session.SessionName,
                    ValuePoint = value,
                    EventContent=scene.Model.Title+":"+scene.Model.Content
                };
                DB.TrainningEvaluations.Add(e);
                scene.Evaluation = e;
            }
            else {
                scene.Evaluation.ValuePoint = value;
            }
            DB.SaveChanges();

            //var m = DB.TrainningEvaluations.Where(v => v.SessionID == cs.Session.ID && v.Group == ScenariosUser.GroupKey).ToList();
            ////return View(m);
            //var vc0=m.Count(v=>v.ValuePoint==0);
            //var vc1=m.Count(v=>v.ValuePoint==1);
            //var vc2=m.Count(v=>v.ValuePoint==2);
            //var tc=cs.SceneList.Count();if(tc==0)tc=100;
            //var result = new { cv = value, ct = valuetitle,rc=m.Count(), vc0 = vc0, vc1 = vc1, vc2 = vc2, vp0 = Math.Round(vc0 * 100d / tc, 0).ToString(), vp1 = Math.Round(vc1 * 100d / tc, 0).ToString(), vp2 = Math.Round(vc2 * 100d / tc, 0).ToString() };
            //return Json(result);

            return Content(valuetitle);
        }


        //GET:			/Examine/Summary			wait,summary
 
        public ActionResult Summary() {
            var cs = GetCurrentSession();
            if (null == cs || !UserTenant.DrillSubjects.Any(s => s.ID == cs.Subject.ID)) { return Redirect("~/Account/LogOff"); }


            //var m = DB.TrainningEvaluations.Where(v=>v.SessionID==cs.Session.ID && v.Group==ScenariosUser.GroupKey).ToList();
            ////return View(m);
            //return Content(m.Sum(v=>v.ValuePoint).ToString());

            var m = DB.TrainningEvaluations.Where(v => v.SessionID == cs.Session.ID && v.Group == ScenariosUser.GroupKey).ToList();
            //return View(m);
            var vc0 = m.Count(v => v.ValuePoint == 0);
            var vc1 = m.Count(v => v.ValuePoint == 1);
            var vc2 = m.Count(v => v.ValuePoint == 2);
            var tc = cs.SceneList.Count(); if (tc == 0) tc = 100;
            var result = new { cv = -2, ct = "", vc0 = vc0, vc1 = vc1, vc2 = vc2, vp0 = Math.Round(vc0 * 100d / tc, 0).ToString(), vp1 = Math.Round(vc1 * 100d / tc, 0).ToString(), vp2 = Math.Round(vc2 * 100d / tc, 0).ToString() };
            return Json(result, JsonRequestBehavior.AllowGet);
        }



    }
}
